//
//  TSTagItem.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/14.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit

class TSTagItem: UIView {
    
    var clickBlock : ((Int,String) -> ())?
    
    var title : String!
    var titleColor : String!
    var fontSize : CGFloat = 12
    var leftMargin : CGFloat = 10
    var topMargin = 4
    var viewWidth : CGFloat = 0
    
    var itemButton : UIButton!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func itemClick() {
        
        if clickBlock != nil {
            clickBlock!(self.tag, itemButton.currentTitle!)
        }
    }
    
    func setupTagItem(title:String) {
        itemButton.setTitle(title, for: .normal)
    }
    
    func titleWidthForTitle() -> CGFloat {
        if title.count == 0 {
            return 0
        } else {
            
            let str = title as NSString
            return str.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontSize)], context: nil).width + leftMargin*2 + 0.5
        }
    }
}

extension TSTagItem {
    
    func setupUI() {
        itemButton = UIButton.init(type: .custom)
        itemButton.setTitleColor(WHITE_COLOR, for: .normal)
        itemButton.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
        itemButton.titleLabel?.lineBreakMode = .byTruncatingTail
        itemButton.addTarget(self, action: #selector(itemClick), for: .touchUpInside)
        addSubview(itemButton)
        itemButton.snp.makeConstraints { (make) in
            make.top.equalTo(topMargin)
            make.bottom.equalTo(-topMargin)
            make.left.equalTo(leftMargin)
            make.right.equalTo(-leftMargin)
        }
    }
}
